package com.gy.interceptor;

import cn.hutool.core.util.StrUtil;
import com.gy.entity.User;
import com.gy.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Map;

@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String LOGIN_USER_KEY = "login:token:";
    private static final Duration LOGIN_USER_TTL = Duration.ofHours(1); // 1小时有效期

    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest.getServletRequest();

            String path = servletRequest.getURI().getPath();
            String[] pathParts = path.split("/");
            String formId = pathParts[pathParts.length - 1];

            if (StrUtil.isBlank(formId)) {
                log.error("缺少formId参数，拒绝握手");
                return false;
            }

            String token = httpRequest.getHeader("Authorization");
            if (token == null) {
                token = httpRequest.getParameter("token");
            }
            if (token == null) {
                log.error("缺少认证token，拒绝握手");
                return false;
            }

            try {
                User loginUser = userService.getLoginUser(token);
                if (loginUser == null) {
                    log.error("用户未登录或登录已过期，拒绝握手");
                    return false;
                }

                // 设置 attributes
                attributes.put("user", loginUser);
                attributes.put("userId", loginUser.getUserId());
                attributes.put("formId", Long.valueOf(formId));

                // 刷新 token 有效期
                String tokenKey = LOGIN_USER_KEY + token;
                stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL);

                return true;
            } catch (Exception e) {
                log.error("获取登录用户信息时发生错误", e);
                return false;
            }
        }
        return false;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {
        // 握手后的处理，如果需要的话
    }
}
